package com.newcoder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.newcoder.entity.Message;
import com.newcoder.entity.User;
import com.newcoder.mapper.MessageMapper;
import com.newcoder.mapper.UserMapper;
import com.newcoder.service.MessageService;
import com.newcoder.util.CommunityConstant;
import com.newcoder.util.ResponseWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yjh
 * @since 2024-12-04 10:03:26
 */
@Service
public class MessageServiceImpl implements MessageService, CommunityConstant {

    @Autowired
    MessageMapper messageMapper;

    @Autowired
    UserMapper userMapper;


    private List<Integer> getLetterIds(Integer userId, List<Message> letterList) {
        List<Integer> ids = new ArrayList<>();

        if (letterList != null) {
            for (Message message : letterList) {
                if (userId.equals(message.getToId()) && message.getStatus() == 0) {
                    ids.add(message.getId());
                }
            }
        }

        return ids;
    }

    private User getLetterTarget(Integer userId, String conversationId) {
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);

        if (userId == id0) {
            return userMapper.selectById(id1);
        } else {
            return userMapper.selectById(id0);
        }
    }

    //查询当前用户所有对话框
    @Override
    public ResponseWrapper getLetterList(Integer userId) {
        if(userId == null){
            return ResponseWrapper.parameterError("参数不能为空！");
        }

        //当前页第一个数据下标offset
        Integer currentNum = 0;
        Integer pageSize = Integer.MAX_VALUE;
        //当前用户的会话数量
        Integer total = messageMapper.selectConversationCount(userId);
        //查询当前用户所有会话列表的最后一条消息（不分页，前端使用懒加载）
        List<Message> list = messageMapper.selectConversations(userId, currentNum, pageSize);
        //为每个对话框查询未读信息的数量（如果有的话）
        List<Map<String, Object>> resList = new ArrayList<>();
        if (list != null) {
            for (Message message : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("ConversationLastMessage", message);
                map.put("ConversationLetterCount", messageMapper.selectLetterCount(message.getConversationId()));
                map.put("ConversationUnreadCount", messageMapper.selectLetterUnreadCount(userId, message.getConversationId()));
                int targetId = userId.equals(message.getFromId())  ? message.getToId() : message.getFromId();
                map.put("ConversationTargetUser", userMapper.selectById(targetId));

                resList.add(map);
            }
        }
        ResponseWrapper wrapper = ResponseWrapper.markSuccess();
        wrapper.getData().put("ConversationsList",resList);         //当前页数据
        wrapper.getData().put("total", total);                  //总数据个数
        return wrapper;
    }

    //详细对话框，查询a-b两者的所有对话信息（考虑使用懒加载）
    @Override
    public ResponseWrapper getLetterDetail(Integer userId, String conversationId) {
        if(conversationId == null){
            return ResponseWrapper.parameterError("参数不能为空！");
        }

        //当前页第一个数据下标offset
        Integer currentNum = 0;
        Integer pageSize = Integer.MAX_VALUE;
        Integer total = messageMapper.selectLetterCount(conversationId);
        //查询当前对话框中的所有消息
        List<Message> list = messageMapper.selectLetters(conversationId, currentNum, pageSize);
        //为每个对话查询接受者name
        List<Map<String, Object>> resList = new ArrayList<>();
        if (list != null) {
            for (Message message : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("letter", message);
                //发送者
                map.put("fromUser", userMapper.selectById(message.getFromId()));
                resList.add(map);
            }
        }
        //修改对话框状态，为已读（将对话框中所有信息设置为已读状态）
        List<Integer> ids = getLetterIds(userId, list);
        if (!ids.isEmpty()) {
            messageMapper.updateStatus(ids, 1);
        }

        ResponseWrapper wrapper = ResponseWrapper.markSuccess();
        wrapper.getData().put("LettersConversationList",resList);         //当前对话框数据
        wrapper.getData().put("total", total);                  //总数据个数
        wrapper.getData().put("target", getLetterTarget(userId, conversationId));
        return wrapper;
    }

    //注意分析，有一个人在聊天界面，两个人都在聊天界面的情况
    @Override
    public ResponseWrapper sendMessage(Message message) {
        if(message == null){
            return ResponseWrapper.parameterError("参数不能为空！");
        }
        if(message.getContent() == null){
            return ResponseWrapper.parameterError("不能发送空消息！");
        }

        //对话框conversationId为aId_bId(a<b),小的id在前，大的id在后
        if (message.getFromId() < message.getToId()) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        } else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        message.setStatus(0);
        message.setCreateTime(new Date());
        int i = messageMapper.insertMessage(message);
        if(i != 1){
            return ResponseWrapper.parameterError("发送失败！");
        }else {
            return ResponseWrapper.markCustom(true, 200,"发送成功！");
        }
    }


    @Override
    public ResponseWrapper getNoticeList(Integer userId, String topic) {
        if(userId == null || topic == null){
            return ResponseWrapper.parameterError("参数不能为空！");
        }

        ResponseWrapper wrapper = ResponseWrapper.markSuccess();

        // 查询评论类通知
        Message message = messageMapper.selectLatestNotice(userId, TOPIC_COMMENT);
        if (message != null) {
            Map<String, Object> messageVO = new HashMap<>();
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userMapper.selectById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));

            int count = messageMapper.selectNoticeCount(userId, TOPIC_COMMENT);
            messageVO.put("count", count);

            int unread = messageMapper.selectNoticeUnreadCount(userId, TOPIC_COMMENT);
            messageVO.put("unread", unread);

            //model.addAttribute("commentNotice", messageVO);
            wrapper.getData().put("commentNotice",messageVO);
        }
        // 查询点赞类通知
        message = messageMapper.selectLatestNotice(userId, TOPIC_LIKE);
        if (message != null) {
            Map<String, Object> messageVO = new HashMap<>();
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userMapper.selectById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));
            messageVO.put("postId", data.get("postId"));

            int count = messageMapper.selectNoticeCount(userId, TOPIC_LIKE);
            messageVO.put("count", count);

            int unread = messageMapper.selectNoticeUnreadCount(userId, TOPIC_LIKE);
            messageVO.put("unread", unread);

            wrapper.getData().put("likeNotice",messageVO);
        }

        // 查询关注类通知
        message = messageMapper.selectLatestNotice(userId, TOPIC_FOLLOW);
        if (message != null) {
            Map<String, Object> messageVO = new HashMap<>();
            messageVO.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVO.put("user", userMapper.selectById((Integer) data.get("userId")));
            messageVO.put("entityType", data.get("entityType"));
            messageVO.put("entityId", data.get("entityId"));

            int count = messageMapper.selectNoticeCount(userId, TOPIC_FOLLOW);
            messageVO.put("count", count);

            int unread = messageMapper.selectNoticeUnreadCount(userId, TOPIC_FOLLOW);
            messageVO.put("unread", unread);

            wrapper.getData().put("followNotice",messageVO);
        }

        // 查询未读消息数量
        int letterUnreadCount = messageMapper.selectLetterUnreadCount(userId, null);
        int noticeUnreadCount = messageMapper.selectNoticeUnreadCount(userId, null);

        wrapper.getData().put("letterUnreadCount",letterUnreadCount);
        wrapper.getData().put("noticeUnreadCount", noticeUnreadCount);
        return wrapper;
    }

    @Override
    public ResponseWrapper getNoticeDetail(Integer userId, String topic) {
        //当前页第一个数据下标offset
        Integer currentNum = 0;
        Integer pageSize = Integer.MAX_VALUE;
        //当前用户的会话数量
        Integer total = messageMapper.selectConversationCount(userId);

        List<Message> noticeList = messageMapper.selectNotices(userId, topic, currentNum, pageSize);
        List<Map<String, Object>> noticeVoList = new ArrayList<>();
        if (noticeList != null) {
            for (Message notice : noticeList) {
                Map<String, Object> map = new HashMap<>();
                // 通知
                map.put("notice", notice);
                // 内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
                map.put("user", userMapper.selectById((Integer) data.get("userId")));
                map.put("entityType", data.get("entityType"));
                map.put("entityId", data.get("entityId"));
                map.put("postId", data.get("postId"));
                // 通知作者
                map.put("fromUser", userMapper.selectById(notice.getFromId()));

                noticeVoList.add(map);
            }
        }
        //model.addAttribute("notices", noticeVoList);

        // 设置已读
        List<Integer> ids = getLetterIds(userId, noticeList);
        if (!ids.isEmpty()) {
            messageMapper.updateStatus(ids, 1);
        }

        ResponseWrapper wrapper = ResponseWrapper.markSuccess();
        wrapper.getData().put("notices",noticeVoList);
        wrapper.getData().put("total", total);
        return wrapper;
    }
}
